<template>
    <div>
        <div class="container">
            <div class="form-box">
                <el-form ref="newsFormRef" :rules="newsFormRules" :model="newsForm" :label-width="formLabelWidth">
					<!-- 资讯常规信息 -->
                    <el-form-item label="文章标题" prop="title">
                        <el-input v-model="newsForm.title" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="资讯栏目" prop="catalogName">
                        <el-input v-model="newsForm.catalogId" class="handle-input mr10" v-if="false"/>
                        <el-input v-model="newsForm.catalogName" placeholder="资讯栏目" clearable readonly class="handle-input mr10" @click="func_loadVCatalogNameDict()"/>
                    </el-form-item>
                    <el-form-item label="文章TAG标签" prop="tags">
                        <el-select v-model="checkedTags" multiple class="handle-select mr10" placeholder="请选择" >
                            <el-option v-for="item in tagCheckOpts" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                        <el-input v-model="newsForm.tags" class="handle-input mr10" v-if="false"></el-input>
                    </el-form-item>
                    <el-form-item label="封面图片">
                        <el-input v-model="newsForm.coverPic" placeholder="封面图片" v-if=false />
						<el-avatar v-if="masterImageUrl" class="avatar" shape="square" :src="masterImageUrl" />
                        <VAvatarUpload v-else v-bind:selectValue="VAvatar" @avatar="func_loadVAvatarData" />
                    </el-form-item>
                    <el-form-item label="文章简讯">
						<el-input type="textarea" rows="5" v-model="newsForm.summary" class="handle-textArea" maxlength="100" show-word-limit />
                    </el-form-item>
                    <el-form-item label="稿件正文"></el-form-item>
					<!-- SEO及广告位设置  -->
                    <el-form-item label="SEO标题" prop="seoWords">
                        <el-input v-model="newsForm.seoWords" class="handle-input mr10" maxlength="50"/>
                    </el-form-item>
                    <el-form-item label="SEO关键词" prop="seoKey">
                        <el-input type="textarea" rows="5" v-model="newsForm.seoKey" class="handle-textArea" maxlength="100" show-word-limit />
                    </el-form-item>
                    <el-form-item label="SEO描述" prop="seoDesp">
						<el-input type="textarea" rows="5" v-model="newsForm.seoDesp" class="handle-textArea" maxlength="100" show-word-limit />
                    </el-form-item>
                    <el-form-item label="分享链接" prop="shareLinks">
                        <el-input v-model="newsForm.shareLinks" class="mr10" style="width:600px">
                            <template #prepend>Http://</template>
                        </el-input>
                    </el-form-item>
					<!-- 其他设置 -->
                    <el-form-item label="原作者" prop="auth">
                        <el-input v-model="newsForm.auth" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="引文来源" prop="sourceFrom">
                        <el-input v-model="newsForm.sourceFrom" class="mr10" style="width:600px">
                            <template #prepend>Http://</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="阅读权限" prop="authRight">
                        <el-input v-model="newsForm.authRight" v-if="false" />
                        <el-select v-model="newsForm.authRight" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in authRightOpts" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="浏览量" prop="readCount">
                        <el-input v-model="newsForm.readCount" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="发布时间" prop="publishTime">
						<el-date-picker type="date" placeholder="选择日期" v-model="newsForm.publishTime" class="handle-input mr10"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="排序" prop="name">
                        <el-input v-model="newsForm.sort" v-if="false"></el-input>
                        <el-input-number v-model="sortNum" :min="1" :max="100" :step="1" style="width:200px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="func_onSubmit" plain>数据提交</el-button>
                        <el-button type="warning" @click="func_onReset" plain>重置数据</el-button>
                        <el-button @click="func_onBack" plain>放弃修改</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <!-- ---------------------------------------------------------------------------------------------------------------------- -->
        <!-- 编辑弹出框 -->
        <el-dialog title="新建资讯栏目" v-model="vNewsCatalogDialogVisible" width="55%" :close-on-click-modal="false">
            <VNewsCatalogDict v-bind:selectValue="vNewsCatalogData" @dictData="func_loadvNewsCatalogData" />
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, toRefs, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import VNewsCatalogDict from "./newsCatalogDict.vue";
import { findNewsInfoById, saveNews } from "../../../../api/hairmanager/news";
import { findNewsTagList } from "../../../../api/hairmanager/newsTag";
import { loadNewsReadPermissionsDict } from "../../../../api/dict";

import VAvatarUpload from '../../../../components/AvatarUpload.vue';

import { NO_DATA_SELECT_ERROR, SUCCESS_DELDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE } from "../../../../api/CommonErrorMessage.js";

export default {
    name: "newsForm",
    components: {VNewsCatalogDict, VAvatarUpload, },
    setup(props, cex){
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
        const authRightOpts = ref([]);
		/**
         * @name 定义业务表单
         */
        const getInitFormData = () => {
            return {
				auth: '',
				authRight: '',
				catalogId: 0,
                catalogName: '',
				coverPic: '',
                summary:'',
				createTime: '',
				htmlJson: '',
				id: 0,
				publishTime: '',
                seoWords: '',
                seoKey: '',
                seoDesp: '',
                sourceFrom: '',
                shareLinks: '',
				sort: 0,
				isStatus: 0,
				tags: '',
				title: '',
                readCount: 0,
			}
        };
        /**
         * @name 表单初始化
         */
        const resetnewsForm = () => {
            Object.assign(newsForm, getInitFormData());
            sortNum.value = 1;
        };
		// 新闻资讯表单数据
        const newsForm = reactive(getInitFormData());
        const newsFormRef = ref(null);
        const newsFormRules = {
            title: [
                { required: true, message: "请输入新闻资讯标题", trigger: "blur" },
            ],
            catalogName: [
                { required: true, message: "请选择一个栏目", trigger: "blur" },
            ],
        };
        const sortNum = ref(1);
        // =========================================================================================
        // 主业务处理 ========================================================================================= START
        // 提交
        const func_onSubmit = () => {
            // 表单校验
            newsFormRef.value.validate((valid) => {
                // 表单校验
                if (valid) {
                    newsForm['tags'] = checkedTags.value.join(",");
                    saveNews(newsForm).then((res) => {
                        if(res.code != 200) {
                            if(res.type == 0) {
                                ElMessage.warning(res.message);
                            } else {
                                ElMessage.error(res.message);
                            }
                        } else {
                            ElMessage.success(SUCCESS_DELDATA_DIALOG_MESSAGE);
                            router.push({path: '/news', query:{load: true }});
                        }
                    });
                } else {
                    return false;
                }
            });
        };
        // 重置
        const func_onReset = () => {
            resetnewsForm();
        };
        const func_onBack = () => {
            router.push({path: '/news', query:{load: true }});
        }
        // 主业务处理 ========================================================================================= END
        // 业务插件处理 ========================================================================================= START
        const vNewsCatalogDialogVisible = ref(false);
        const vNewsCatalogData = ref({
            load: false,
            id: 0,
        });
        const func_loadVCatalogNameDict = () => {
            vNewsCatalogDialogVisible.value = true;
        };
        const func_loadvNewsCatalogData = (v) => {
            newsForm['catalogId'] = v['dicCode'];
            newsForm['catalogName'] = v['dicName'];
            vNewsCatalogDialogVisible.value = false;
        };
        const loadDataFlg = ref(null);
        const loadNewsId = ref(null);
        const tagCheckOpts = ref([]);
        const checkedTags = ref([]);
        const func_onload = () => {
            authRightOpts.value = [];
            loadNewsReadPermissionsDict().then((res) => {
                res.data.forEach((item) => {
                    let obj = {value : item['value'], label : item['label']}
                    authRightOpts.value.unshift(obj);
                });
            });
            tagCheckOpts.value = [];
            findNewsTagList().then((res) => {
                res.data.forEach((item) => {
                    let obj = {value : item['value'], label : item['label']}
                    tagCheckOpts.value.unshift(obj);
                });
            });
        };
        func_onload();
		// 主图上传 ========================================================================================= START
        let masterImageUrl = ref('');
        const VAvatar = reactive({});
        const func_loadVAvatarData = (v) => {
            if(v['state'] === 1) {
                masterImageUrl.vlaue = v['imgUrl'];
                newsForm['coverPic'] = v['imgUrl'];
            }
        };
        // 主图上传 ========================================================================================= END
        // =========================================================================================
        // 业务数据监听
        watch(() => route.query, (val) => {
            loadDataFlg.value = val['load'];
            loadNewsId.value = val['newsId'];
			if(loadDataFlg.value === '1'){
                findNewsInfoById(loadNewsId.value).then((res) =>{
                    Object.keys(newsForm).forEach((item) => {
                        newsForm[item] = res.data[item];
                    });
                    masterImageUrl.value = res.data['coverPic'];
                    checkedTags.value = res.data['tagsList'];
                }); 
			} else {
                resetnewsForm();
            }

        },{deep: true,immediate: true});
        // 业务插件处理 ========================================================================================= END
        return {
			// 系统变量
            formLabelWidth, newsForm, newsFormRef, newsFormRules, sortNum, authRightOpts, tagCheckOpts, checkedTags, loadDataFlg, loadNewsId,
			// 主业务调用方法
            getInitFormData, resetnewsForm, func_onSubmit, func_onReset, func_onBack,
            // 业务插件处理
            vNewsCatalogDialogVisible, vNewsCatalogData, func_loadVCatalogNameDict, func_loadvNewsCatalogData,
			// =========================================================================================
            // 图片文件处理
            masterImageUrl, VAvatar, func_loadVAvatarData,
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 600px;
}

.handle-input {
    width: 600px;
    display: inline-block;
}

.handle-textArea {
    width: 600px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.avatar {
    width: 100%;
    height: 100%;
    display: block;
    align: center;
}
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>